<template>
  <div class="box">
    <TopSearch
      @searchHeader="searchHeader"
      @delsHeader="delsHeader"
      @addHeader="addHeader"
      @headerButtonDel="headerButtonDel"
      @headerButtonSearch="headerButtonSearch"
      @headerButtonSelect="headerButtonSelect"
      :control="control"
      :controlPosition="controlPosition"
      :positionName="positionName"
      :disabled="disabled"
      :delsable="delsable"
      :searchConfig="setFormConfig"
    />
    <ProTable
      class="protable"
      :data="tableData"
      :page="page"
      :column="column"
      :rowControl="rowControl"
      :elProps="elProps"
      :disabled="disabled"
      :controlWidth="controlWidth"
      @row-control-click="onRowControlClick"
      @selection-change="onSelectionChange"
      @page-change="onPageChange"
      @pageRefresh="pageRefresh"
    >
      <template #default="{ row, propname }">
        <div v-if="propname === 'role'">
          {{row[propname] && row[propname].role_name ? row[propname].role_name : row[propname]}}
        </div>
      </template>
    </ProTable>

    <FouDialog
      :title="'添加/修改'"
      :width="'75%'"
      v-model:dialogValue="dialogValue"
    >
      <template #content>
        <div>
          <AddEdit
            ref="AddEditref"
            :echo="echo"
            :school="school"
            :rules="rules"
            :position="position"
          ></AddEdit>
        </div>
      </template>
      <template #footer>
        <div>
          <el-button @click="cancel">取消</el-button>
          <el-button
            type="primary"
            @click="confirm(buttonType)"
            color="#081F42"
            >確定</el-button
          >
        </div>
      </template>
    </FouDialog>

    <FouDialog
      :title="'職位'"
      :width="'75%'"
      v-model:dialogValue="searchDiolog"
    >
      <template #content>
        <div>
          <searchDia @search-dialog="searchDialog"></searchDia>
        </div>
      </template>
      <template #footer>
        <div>
          <el-button @click="searchDiolog = false">取消</el-button>
        </div>
      </template>
    </FouDialog>
  </div>
</template>

<script setup>
import { nextTick, reactive, ref, onMounted } from "vue";
import { elProps, options, controlWidth } from "./index.js";
import { setFormConfig, DialogConfig } from "./formConfig";
import AddEdit from "./AddEdit/index.vue";
import searchDia from "./searchDia/index.vue";
import {
  teacherList,
  SchoolList,
  role,
  addTeacher,
  updateTeacher,
  deleteTeacher,
} from "@/http/index.js";
import { addeditConfig } from "./AddEdit/formConfig";
import {
  message,
  messageBox,
  loading,
  closeLoading,
} from "@/common/function.js";
const buttonType = ref("");
const updateTeacherList = async (e) => {
  const data = await updateTeacher(e);
  console.log(data);
  if (data.code == 200) {
    loading()
    await TableList();
    message("修改教师资料成功");
    closeLoading()
  }
};
const addTeacherList = async (e) => {
  const data = await addTeacher(e);
  if (data.code == 200) {
    loading()
    await TableList();
    message("添加教師成功");
    closeLoading()
  }
};
let echo = ref({});

//搜索彈窗
const searchDiolog = ref(false);
const headerButtonSearch = () => {
  searchDiolog.value = true;
};

const searchDialog = (row, type) => {
  searchDiolog.value = false;
  console.log(row, type);
  positionName.value = row.name
};

// 添加編輯彈窗
const AddEditref = ref("");
const confirm = (type) => {
  AddEditref.value.DialogCofirm(async (e) => {
    console.log(e);
    if (e) {
          if (e.school_id) {
      e.school_id = e.school_id.toString();
    }
    if (type == "add") {
      if (e.id) {
        delete e.id;
      }
      await addTeacherList(e);
    } else if (type == "edit") {
      await updateTeacherList(e);
    } 
   dialogValue.value = false
    }

  });
};
const cancel = (formEl) => {};

// 分页数据（不给就没有分页）
const page = reactive({
  current_page: 1, //当前页
  per_page: 10, //每页条数
  total: 0, //总条数
  page_size: [10, 20, 30], //可选分页条数
});
const search = ref({
  name: "",
  status: "",
  time: "",
});
const searchHeader = (e, type) => {
  Object.assign(obj, e);
    TableList();
};
// 字段名对应表头
const column = {
  username: "職員登入名",
  name: "中文名",
  ename: "英文名",
  role:'職位',
  email: "郵箱",
  mobile: "手機號",

  create_time: "創建時間",
};
// 表格顶部操作按钮
const control = ["search", "dels", "add"];
const controlPosition = [];
const positionName = ref("");

// 未选中数据是 禁用项
const disabled = ["dels"];
const delsable = ref(true);

const headerButtonDel = () => {
  console.log("headerButtonDel");
  positionName.value = ''

};

const headerButtonSelect = () => {
  console.log("headerButtonSelect");
};

const dialogValue = ref(false);
const rules = reactive({
        username: {
            required: true,
            message: '请填写登入名',
            trigger: ['blur', 'change'],
        },
        password:{
            required: true,
            message: '请填写密码',
            trigger: ['blur', 'change'],
        },
        belong_school:{
            required: true,
            message: '请选择归属学校',
            trigger: ['blur', 'change'],
        },
        school_id:{
            required: true,
            message: '请选择可选学校',
            trigger: ['blur', 'change'],
        },
        status:{
            required: true,
            message: '请选择状态',
            trigger: ['blur', 'change'],
        },
        role_id:{
            required: true,
            message: '请选择职位',
            trigger: ['blur', 'change'],
        },
    })
const addHeader = async () => {
    await schoolSelect();
  await roleApiSelect();
  buttonType.value = "add";
  echo.value = {
          id:'',
      username:'',
      password:'',
      email:'',
      mobile:'',
      name:'',
      ename:'',
      belong_school:'',
      school_id:'',
      role_id:'',
      status:'',
      color:'',
  }
  rules.password = [{ required: true, message: "請輸入密碼", trigger:  ["blur",'change']  }]
  // loading()
  //        await schoolSelect();
  //  await roleApiSelect()
  //  closeLoading()
  dialogValue.value = true;
};
const position = ref([]);
const roleApiSelect = async () => {
  const data = await role();
  if (data.code == 200) {
    data.data.data.map((e) => {
      (e.label = e.role_name), (e.value = e.id);
    });
    position.value = data.data.data;
  } else {
    message("职位請求超時請稍後重試", "warning");
  }
};
const school = ref([]);
const schoolSelect = async () => {
  let fromobj = {
    page: 1,
    limit: 100,
    name: "",
    status: "",
    time: "",
  };
  const data = await SchoolList(fromobj);
  if (data.code == 200) {
    data.data.data.map((e) => {
      (e.label = e.name), (e.value = e.id);
    });
    school.value = data.data.data;
  } else {
    message("学校請求超時請稍後重試", "warning");
  }
};
// 表格行内操作按钮
const rowControl = ["rowedit", "rowdel"];

/**表格行内操作
 * @row {object} 行内数据
 * @type {string} 点击按钮类型
 */
const onRowControlClick = async ({ scope: { row }, type }) => {
  console.log(row, type);
  buttonType.value = "edit";

  if (type == "rowedit") {
      await schoolSelect();
  await roleApiSelect();
    if (row.school_id &&  typeof(row.school_id) == 'string') {
      row.school_id = row.school_id.split(",").map(Number);
    }
    // loading()
    //        await schoolSelect();
    //  await roleApiSelect()
    // closeLoading()
    const {
      id,
      username,
      password,
      email,
      mobile,
      name,
      ename,
      belong_school,
      school_id,
      role_id,
      status,
      color,
    } = row;
    echo.value = {
      id,
      username,
      password,
      email,
      mobile,
      name,
      ename,
      belong_school,
      school_id,
      role_id,
      status,
      color,
    };
    rules.password = [{required: false}]
    console.log(echo.value);
    dialogValue.value = true;
  }
  if (type == "rowdel") {
    messageBox().then(async () => {
        await delTableList(row.id)
    });
  }
};
const delTableList = async (id)=>{
      const data = await deleteTeacher(id);
      console.log(data);
      if (data.code == 200) {
       await TableList();
       message('成功刪除教師')
      }
}
/** 多选
 * @selected {Array} 被选中的行
 */
const ids = ref('')
const onSelectionChange = (e) => {
    let row_id = []
  e.forEach(e => {
    row_id.push(e.id)
  });
  ids.value = row_id.toString()
  delsable.value = e.length === 0;
};
const delsHeader = async () => {
      messageBox().then(async () => {
  await delTableList(ids.value)
    });

};
/**
 * @e {number} 分页操作后的值（当前页|改变后的每页条数）
 * @type {string} <current|size> 分页操作类型（当前页改变|每页条数改变）
 */
const onPageChange =async ({ e, type }) => {
  if (type == "current") {
    obj.page = e
  }
  if (type == "size") {
     obj.page = 1
    obj.limit = e
  }
   await TableList()
};
const tableData = ref([]);
const obj = reactive({
  school_id:localStorage.getItem('school_id'),
  page: page.current_page,
  limit: page.per_page,
  name: "",
  status: "",
  time: "",
});
const TableList = async () => {
  loading()
  const data = await teacherList(obj);
  console.log(data);
  if (data.code == 200) {
    tableData.value = data.data.data;
    page.current_page = data.data.current_page;
    page.per_page = data.data.per_page;
    page.total = data.data.total;
  }
  closeLoading()
};
const pageRefresh = async() => {
  loading()
  await TableList()
  closeLoading()
};
onMounted(async () => {
  TableList();

});
// 弹窗
const dialogVisible = ref(false);

const handleClose = (done) => {
  dialogVisible.value = false;
};
</script>

<style lang="less" scoped>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.box {
  padding: 16px 33px;
}
</style>